package com.ap.core.email.xml.datatype.converter;

import org.apache.commons.lang.StringUtils;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 * Custom XML date type conversion for JAXB binding.
 */
public class XMLDateTypeConverter {

    private static final DatatypeFactory DATA_TYPE_FACTORY;

    static {
        try {
            DATA_TYPE_FACTORY = DatatypeFactory.newInstance();
        } catch (DatatypeConfigurationException e) {
            throw new AssertionError(e);
        }
    }

    private XMLDateTypeConverter() {
        super();
    }

    /**
     * Marshal localData to XMLdateTime lexical representation.
     *
     * @param localDate- local date
     * @return lexical xml date
     */
    public static String printDateTime(LocalDate localDate) {
        final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
        return localDate.toString(dateTimeFormatter);
    }

    /**
     * Convert Lexical xmlDate time string to local date.
     *
     * @param lexicalXSDDate lexical XML date, which may contains white spaces according to specs.
     * @return local date
     */
    public static LocalDate parseDateTime(String lexicalXSDDate) {
        XMLGregorianCalendar date = DATA_TYPE_FACTORY.newXMLGregorianCalendar(StringUtils.deleteWhitespace(lexicalXSDDate));
        return new LocalDate(date.getYear(), date.getMonth(), date.getDay());
    }

}

